import React, { useState, useEffect, useRef } from 'react';
import Editor from '@monaco-editor/react';
import mermaid from 'mermaid';
import { Copy, Download, RotateCcw, FileText, GitBranch, Box, Database, Calendar, Play, ChevronRight, Info, Palette, Eye, Code, X } from 'lucide-react';
import { templates, templateCategories } from "../../data/chartTemplates";
import { chartDocumentation as chartDocs } from "../../data/chartDocs";
import Tooltip from "../components/Tooltip";

// Configure Monaco Editor to use local files instead of CDN
import { loader } from '@monaco-editor/react';

// Monaco Editor 配置 - 优先加载本地，失败时使用CDN
async function configureMonacoLoader() {
  try {
    await import('monaco-editor/esm/vs/editor/editor.api');
    console.log('使用本地monaco-editor (ESM方式)');
    loader.config({ paths: { vs: '/node_modules/monaco-editor/min/vs' } });
  } catch (error) {
    console.log('本地monaco-editor加载失败，使用CDN:', error.message);
    loader.config({ paths: { vs: 'https://cdn.jsdelivr.net/npm/monaco-editor@0.44.0/min/vs' } });
  }
}

configureMonacoLoader();

// Define Mermaid language for Monaco Editor
const defineMermaidLanguage = (monaco) => {
  monaco.languages.register({ id: 'mermaid' });
  
  monaco.languages.setMonarchTokensProvider('mermaid', {
    tokenizer: {
      root: [
        [/(flowchart|sequenceDiagram|classDiagram|stateDiagram|erDiagram|gantt|pie|graph|journey|requirementDiagram|gitGraph|C4Context|C4Container|C4Component|C4Deployment|mindmap|timeline|title|section|subgraph|end|direction|TB|BT|RL|LR|TD)\b/, 'keyword'],
        [/(participant|actor|activate|deactivate|destroy|create|alt|opt|loop|par|critical|break|rect|link|over|left of|right of|links|note|autonumber|accTitle|accDescription)\b/, 'sequence-specific'],
        [/(class|interface|enum|abstract|static|public|private|protected|package|annotation|classDef)\b/, 'class-specific'],
        [/(state|stateDiagram-v2|as|entry|exit|do|history|deep history|final)\b/, 'state-specific'],
        [/(entity|relationship|one to one|one to many|many to one|many to many|table|column|primary key|foreign key|index|constraint)\b/, 'er-specific'],
        [/(dateFormat|axisFormat|todayMarker|tickInterval|excludes|includes|task|milestone|crit|done|after|before|id)\b/, 'gantt-specific'],
        [/(requirement|element|relationship|type|text|risk|verifyMethod)\b/, 'requirement-specific'],
        [/(commit|branch|checkout|merge|cherry-pick|rebase|reset|tag|HEAD|master|main|develop|feature|release|hotfix)\b/, 'git-specific'],
        [/(style|click|call|callback|href|callURL|clickURL|linkStyle)\b/, 'function'],
        [/(config|init|theme|themeVariables|securityLevel)\b/, 'type'],
        [/%%.*/, 'comment'],
        [/#.*/, 'comment'],
        [/-->/, 'string'],
        [/--/, 'string'],
        [/->>/, 'string'],
        [/->/, 'string'],
        [/-/, 'string'],
        [/<-->/, 'string'],
        [/<--/, 'string'],
        [/<</, 'string'],
        [/<-/, 'string'],
        [/[{}[\]()|]/, 'delimiter'],
        [/\[/, 'delimiter', '@bracket_content'],
        [/\{/, 'delimiter', '@brace_content'],
        [/'([^'\\]|\\.)*$/, 'string.invalid'],
        [/'/, 'string', '@string'],
        [/"([^"\\]|\\.)*$/, 'string.invalid'],
        [/"/, 'string', '@string_double'],
        [/\d+/, 'number'],
        [/\w+/, 'identifier']
      ],
      string: [
        [/[^\\']+/, 'string'],
        [/\\./, 'string.escape'],
        [/'/, 'string', '@pop']
      ],
      string_double: [
        [/[^\\"]+/, 'string'],
        [/\\./, 'string.escape'],
        [/"/, 'string', '@pop']
      ],
      bracket_content: [
        [/[^\]]+/, 'bracket-content'],
        [/\]/, 'delimiter', '@pop']
      ],
      brace_content: [
        [/[^}]+/, 'brace-content'],
        [/\}/, 'delimiter', '@pop']
      ]
    }
  });
  
  // Define theme colors for Mermaid language
  monaco.editor.defineTheme('mermaid', {
    base: 'vs',
    inherit: true,
    rules: [
      { token: 'keyword', foreground: '#0000FF', fontStyle: 'bold' },
      { token: 'function', foreground: '#008000', fontStyle: 'bold' },
      { token: 'sequence-specific', foreground: '#DC143C', fontStyle: 'bold' },
      { token: 'class-specific', foreground: '#006400', fontStyle: 'bold' },
      { token: 'state-specific', foreground: '#008B8B', fontStyle: 'bold' },
      { token: 'er-specific', foreground: '#8B008B', fontStyle: 'bold' },
      { token: 'gantt-specific', foreground: '#8B4513', fontStyle: 'bold' },
      { token: 'requirement-specific', foreground: '#FF69B4', fontStyle: 'bold' },
      { token: 'git-specific', foreground: '#FF8C00', fontStyle: 'bold' },
      { token: 'type', foreground: '#800080', fontStyle: 'bold' },
      { token: 'comment', foreground: '#808080', fontStyle: 'italic' },
      { token: 'string', foreground: '#FF8C00', fontStyle: 'bold' },
      { token: 'string.escape', foreground: '#FF6347', fontStyle: 'bold' },
      { token: 'string.invalid', foreground: '#FF0000', fontStyle: 'italic' },
      { token: 'delimiter', foreground: '#383838', fontStyle: 'bold' },
      { token: 'bracket-content', foreground: '#00008B', fontStyle: 'bold' },
      { token: 'brace-content', foreground: '#00008B', fontStyle: 'bold' },
      { token: 'number', foreground: '#008080', fontStyle: 'bold' },
      { token: 'identifier', foreground: '#000000' }
    ],
    colors: {
      'editor.background': '#F8FAFC',
      'editor.foreground': '#1F2937',
      'editor.lineHighlightBackground': '#E0F2FE',
      'editor.selectionBackground': '#DBEAFE',
      'editor.selectionForeground': '#1F2937',
      'editor.inactiveSelectionBackground': '#DBEAFE'
    }
  });
};

// Initialize mermaid
mermaid.initialize({
  startOnLoad: true,
  theme: 'default',
  securityLevel: 'loose',
  themeVariables: {
    primaryColor: '#4CAF50',
    primaryTextColor: '#333',
    primaryBorderColor: '#4CAF50',
    lineColor: '#333',
    secondaryColor: '#8BC34A',
    tertiaryColor: '#CDDC39',
    background: '#ffffff',
    mainBkg: '#ffffff',
    secondBkg: '#f5f5f5',
  },
  gantt: {
    useMaxWidth: false,
    barHeight: 20,
    barGap: 4,
    topPadding: 50,
    leftPadding: 100,
    gridLineStartPadding: 35,
    fontSize: 14,
    fontFamily: 'sans-serif',
    numberSectionStyles: 4,
    axisFormat: '%Y-%m-%d',
    startDate: new Date().toISOString().split('T')[0],
    minDateWidth: 100,
    labelFormat: { 
      day: '%d',
      week: '%U',
      month: '%m月',
      quarter: '%q',
      year: '%Y'
    },
    allowNegativeValues: false
  }
});

const MermaidEditor = () => {
  const [code, setCode] = useState(templates.flowchart);
  const [error, setError] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [editorReady, setEditorReady] = useState(false);
  const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
  const [expandedCategories, setExpandedCategories] = useState({});
  const [showChartDocs, setShowChartDocs] = useState(false);
  const [currentChartType, setCurrentChartType] = useState('flowchart');
  const [editorWidth, setEditorWidth] = useState(50);
  const [showCustomThemeModal, setShowCustomThemeModal] = useState(false);
  const [customThemeColors, setCustomThemeColors] = useState({
    primaryColor: '#4CAF50',
    primaryTextColor: '#ffffff',
    primaryBorderColor: '#388E3C',
    lineColor: '#333333',
    secondaryColor: '#8BC34A',
    tertiaryColor: '#CDDC39',
    background: '#ffffff',
    mainBkg: '#f5f5f5',
    secondBkg: '#eeeeee',
    nodeBorder: '#388E3C',
    clusterBkg: '#f5f5f5',
    clusterBorder: '#cccccc',
    defaultLinkColor: '#333333',
    titleColor: '#333333',
    edgeLabelBackground: '#ffffff',
    nodeTextColor: '#ffffff'
  });
  
  const diagramRef = useRef(null);
  const isResizing = useRef(false);
  
  // 缩放和背景状态
  const [scale, setScale] = useState(1);
  const [minScale] = useState(0.1);
  const [maxScale] = useState(5);
  const [zoomStep] = useState(0.1);
  const [backgroundColor, setBackgroundColor] = useState('#ffffff');
  const [backgroundPattern, setBackgroundPattern] = useState('none');
  const [currentTheme, setCurrentTheme] = useState('default');
  const [showMiniMap, setShowMiniMap] = useState(true);
  const [translateX, setTranslateX] = useState(0);
  const [translateY, setTranslateY] = useState(0);
  
  const miniMapRef = useRef(null);
  const viewportRef = useRef(null);
  
  // Mermaid主题配置
  const mermaidThemes = {
    default: {
      name: '默认主题',
      theme: 'default',
      themeVariables: {
        primaryColor: '#4CAF50',
        primaryTextColor: '#333',
        primaryBorderColor: '#4CAF50',
        lineColor: '#333',
        secondaryColor: '#8BC34A',
        tertiaryColor: '#CDDC39',
        background: '#ffffff',
        mainBkg: '#ffffff',
        secondBkg: '#f5f5f5',
        nodeBorder: '#4CAF50',
        clusterBkg: '#f5f5f5',
        clusterBorder: '#ddd',
        defaultLinkColor: '#333',
        titleColor: '#333',
        edgeLabelBackground: '#ffffff',
        nodeTextColor: '#333'
      }
    },
    forest: {
      name: '森林主题',
      theme: 'forest',
      themeVariables: {
        primaryColor: '#268426',
        primaryTextColor: '#ffffff',
        primaryBorderColor: '#1a5c1a',
        lineColor: '#1a5c1a',
        secondaryColor: '#3a9b3a',
        tertiaryColor: '#4caf50',
        background: '#f9f9f9',
        mainBkg: '#ffffff',
        secondBkg: '#f0f8f0',
        nodeBorder: '#1a5c1a',
        clusterBkg: '#f0f8f0',
        clusterBorder: '#3a9b3a',
        defaultLinkColor: '#1a5c1a',
        titleColor: '#1a5c1a',
        edgeLabelBackground: '#ffffff',
        nodeTextColor: '#1a5c1a'
      }
    },
    dark: {
      name: '暗黑主题',
      theme: 'dark',
      themeVariables: {
        primaryColor: '#bb86fc',
        primaryTextColor: '#ffffff',
        primaryBorderColor: '#bb86fc',
        lineColor: '#ffffff',
        secondaryColor: '#03dac6',
        tertiaryColor: '#cf6679',
        background: '#121212',
        mainBkg: '#1e1e1e',
        secondBkg: '#2d2d2d',
        nodeBorder: '#bb86fc',
        clusterBkg: '#1e1e1e',
        clusterBorder: '#333',
        defaultLinkColor: '#ffffff',
        titleColor: '#ffffff',
        edgeLabelBackground: '#121212',
        nodeTextColor: '#ffffff'
      }
    },
    neutral: {
      name: '中性主题',
      theme: 'neutral',
      themeVariables: {
        primaryColor: '#616161',
        primaryTextColor: '#212121',
        primaryBorderColor: '#424242',
        lineColor: '#212121',
        secondaryColor: '#9e9e9e',
        tertiaryColor: '#bdbdbd',
        background: '#fafafa',
        mainBkg: '#ffffff',
        secondBkg: '#f5f5f5',
        nodeBorder: '#424242',
        clusterBkg: '#f5f5f5',
        clusterBorder: '#e0e0e0',
        defaultLinkColor: '#212121',
        titleColor: '#212121',
        edgeLabelBackground: '#ffffff',
        nodeTextColor: '#212121'
      }
    },
    blue: {
      name: '蓝色主题',
      theme: 'base',
      themeVariables: {
        primaryColor: '#1565C0',
        primaryTextColor: '#0D47A1',
        primaryBorderColor: '#0D47A1',
        lineColor: '#0D47A1',
        secondaryColor: '#42A5F5',
        tertiaryColor: '#90CAF9',
        background: '#e3f2fd',
        mainBkg: '#ffffff',
        secondBkg: '#bbdefb',
        nodeBorder: '#0D47A1',
        clusterBkg: '#bbdefb',
        clusterBorder: '#90caf9',
        defaultLinkColor: '#0D47A1',
        titleColor: '#0D47A1',
        edgeLabelBackground: '#ffffff',
        nodeTextColor: '#0D47A1'
      }
    },
    purple: {
      name: '紫色主题',
      theme: 'base',
      themeVariables: {
        primaryColor: '#6A1B9A',
        primaryTextColor: '#4A148C',
        primaryBorderColor: '#4A148C',
        lineColor: '#4A148C',
        secondaryColor: '#AB47BC',
        tertiaryColor: '#CE93D8',
        background: '#f3e5f5',
        mainBkg: '#ffffff',
        secondBkg: '#e1bee7',
        nodeBorder: '#4A148C',
        clusterBkg: '#e1bee7',
        clusterBorder: '#ce93d8',
        defaultLinkColor: '#4A148C',
        titleColor: '#4A148C',
        edgeLabelBackground: '#ffffff',
        nodeTextColor: '#4A148C'
      }
    },
    orange: {
      name: '橙色主题',
      theme: 'base',
      themeVariables: {
        primaryColor: '#EF6C00',
        primaryTextColor: '#E65100',
        primaryBorderColor: '#E65100',
        lineColor: '#E65100',
        secondaryColor: '#FFB74D',
        tertiaryColor: '#FFCC02',
        background: '#fff3e0',
        mainBkg: '#ffffff',
        secondBkg: '#ffe0b2',
        nodeBorder: '#E65100',
        clusterBkg: '#ffe0b2',
        clusterBorder: '#ffcc02',
        defaultLinkColor: '#E65100',
        titleColor: '#E65100',
        edgeLabelBackground: '#ffffff',
        nodeTextColor: '#E65100'
      }
    },
    red: {
      name: '红色主题',
      theme: 'base',
      themeVariables: {
        primaryColor: '#D32F2F',
        primaryTextColor: '#B71C1C',
        primaryBorderColor: '#B71C1C',
        lineColor: '#B71C1C',
        secondaryColor: '#EF5350',
        tertiaryColor: '#FFCDD2',
        background: '#ffebee',
        mainBkg: '#ffffff',
        secondBkg: '#ffcdd2',
        nodeBorder: '#B71C1C',
        clusterBkg: '#ffcdd2',
        clusterBorder: '#ef9a9a',
        defaultLinkColor: '#B71C1C',
        titleColor: '#B71C1C',
        edgeLabelBackground: '#ffffff',
        nodeTextColor: '#B71C1C'
      }
    },
    teal: {
      name: '青绿主题',
      theme: 'base',
      themeVariables: {
        primaryColor: '#00695C',
        primaryTextColor: '#004D40',
        primaryBorderColor: '#004D40',
        lineColor: '#004D40',
        secondaryColor: '#26A69A',
        tertiaryColor: '#80CBC4',
        background: '#e0f2f1',
        mainBkg: '#ffffff',
        secondBkg: '#b2dfdb',
        nodeBorder: '#004D40',
        clusterBkg: '#b2dfdb',
        clusterBorder: '#80cbc4',
        defaultLinkColor: '#004D40',
        titleColor: '#004D40',
        edgeLabelBackground: '#ffffff',
        nodeTextColor: '#004D40'
      }
    },
    corporate: {
      name: '企业主题',
      theme: 'base',
      themeVariables: {
        primaryColor: '#2C3E50',
        primaryTextColor: '#ffffff',
        primaryBorderColor: '#1a252f',
        lineColor: '#34495E',
        secondaryColor: '#3498DB',
        tertiaryColor: '#ECF0F1',
        background: '#ffffff',
        mainBkg: '#ecf0f1',
        secondBkg: '#d5dbdb',
        nodeBorder: '#1a252f',
        clusterBkg: '#d5dbdb',
        clusterBorder: '#85929e',
        defaultLinkColor: '#34495E',
        titleColor: '#2C3E50',
        edgeLabelBackground: '#ffffff',
        nodeTextColor: '#ffffff'
      }
    },
    custom: {
      name: '自定义主题',
      theme: 'base',
      themeVariables: {
        primaryColor: '#4CAF50',
        primaryTextColor: '#ffffff',
        primaryBorderColor: '#388E3C',
        lineColor: '#333333',
        secondaryColor: '#8BC34A',
        tertiaryColor: '#CDDC39',
        background: '#ffffff',
        mainBkg: '#f5f5f5',
        secondBkg: '#eeeeee',
        nodeBorder: '#388E3C',
        clusterBkg: '#f5f5f5',
        clusterBorder: '#cccccc',
        defaultLinkColor: '#333333',
        titleColor: '#333333',
        edgeLabelBackground: '#ffffff',
        nodeTextColor: '#ffffff'
      }
    }
  };
  
  // 主题变量标签映射
  const themeVariableLabels = {
    primaryColor: '主色调',
    primaryTextColor: '主文本颜色',
    primaryBorderColor: '主边框颜色',
    lineColor: '线条颜色',
    secondaryColor: '次要颜色',
    tertiaryColor: '第三颜色',
    background: '背景色',
    mainBkg: '主背景色',
    secondBkg: '次背景色',
    nodeBorder: '节点边框色',
    clusterBkg: '群组背景色',
    clusterBorder: '群组边框色',
    defaultLinkColor: '默认连接颜色',
    titleColor: '标题颜色',
    edgeLabelBackground: '边标签背景色',
    nodeTextColor: '节点文本颜色'
  };
  
  // 渲染图表函数
  const renderDiagram = async () => {
    if (!diagramRef.current || !code) return;
    
    setIsLoading(true);
    setError('');
    
    try {
      diagramRef.current.innerHTML = '';
      const id = `mermaid-${Date.now()}`;
      
      const chartType = detectChartType(code);
      console.log('渲染图表类型:', chartType);
      console.log('图表代码:', code.substring(0, 100) + '...');
      
      const isValid = await mermaid.parse(code);
      console.log('语法验证结果:', isValid);
      
      if (isValid) {
        const { svg } = await mermaid.render(id, code);
        diagramRef.current.innerHTML = svg;
        
        setTimeout(() => {
          updateMiniMap();
          setupMiniMapDrag();
        }, 100);
      } else {
        setError(`图表语法验证失败，类型: ${chartType}`);
      }
    } catch (err) {
      console.error('图表渲染错误:', err);
      setError(`图表渲染失败: ${err.message || '未知错误'}，请检查图表语法`);
    } finally {
      setIsLoading(false);
    }
  };
  
  // 当代码或主题改变时重新渲染图表
  useEffect(() => {
    renderDiagram();
  }, [code, currentTheme]);
  
  // 主题切换函数
  const handleThemeChange = (themeId) => {
    setCurrentTheme(themeId);
    const themeConfig = mermaidThemes[themeId];
    
    const themeVariables = themeId === 'custom' ? customThemeColors : themeConfig.themeVariables;
    
    mermaid.initialize({
      startOnLoad: true,
      theme: themeConfig.theme,
      securityLevel: 'loose',
      themeVariables: themeVariables,
      flowchart: {
        useMaxWidth: true,
        htmlLabels: true,
        curve: 'basis'
      },
      gantt: {
        useMaxWidth: false,
        barHeight: 20,
        barGap: 4,
        topPadding: 50,
        leftPadding: 100,
        gridLineStartPadding: 35,
        fontSize: 14,
        fontFamily: 'sans-serif',
        numberSectionStyles: 4,
        axisFormat: '%Y-%m-%d',
        startDate: new Date().toISOString().split('T')[0],
        minDateWidth: 100,
        labelFormat: { 
          day: '%d',
          week: '%U',
          month: '%m月',
          quarter: '%q',
          year: '%Y'
        },
        allowNegativeValues: false
      }
    });
    
    renderDiagram();
  };
  
  // 自定义主题相关函数
  const openCustomThemeModal = () => {
    setShowCustomThemeModal(true);
  };
  
  const closeCustomThemeModal = () => {
    setShowCustomThemeModal(false);
  };
  
  const handleCustomColorChange = (colorKey, colorValue) => {
    setCustomThemeColors(prev => ({
      ...prev,
      [colorKey]: colorValue
    }));
  };
  
  const applyCustomTheme = () => {
    mermaidThemes.custom.themeVariables = { ...customThemeColors };
    handleThemeChange('custom');
    closeCustomThemeModal();
  };
  
  const resetCustomTheme = () => {
    const defaultCustomColors = {
      primaryColor: '#4CAF50',
      primaryTextColor: '#ffffff',
      primaryBorderColor: '#388E3C',
      lineColor: '#333333',
      secondaryColor: '#8BC34A',
      tertiaryColor: '#CDDC39',
      background: '#ffffff',
      mainBkg: '#f5f5f5',
      secondBkg: '#eeeeee',
      nodeBorder: '#388E3C',
      clusterBkg: '#f5f5f5',
      clusterBorder: '#cccccc',
      defaultLinkColor: '#333333',
      titleColor: '#333333',
      edgeLabelBackground: '#ffffff',
      nodeTextColor: '#ffffff'
    };
    
    setCustomThemeColors(defaultCustomColors);
    mermaidThemes.custom.themeVariables = { ...defaultCustomColors };
    
    if (currentTheme === 'custom') {
      handleThemeChange('custom');
    }
  };
  
  // 处理调整大小的开始
  const handleResizeStart = (e) => {
    isResizing.current = true;
    document.addEventListener('mousemove', handleMouseMove);
    document.addEventListener('mouseup', handleMouseUp);
    e.preventDefault();
  };
  
  const handleMouseMove = (e) => {
    if (!isResizing.current) return;
    
    const editorContainer = document.querySelector('.editor-container');
    if (!editorContainer) return;
    
    const containerRect = editorContainer.getBoundingClientRect();
    const newWidth = ((e.clientX - containerRect.left) / containerRect.width) * 100;
    const clampedWidth = Math.max(20, Math.min(80, newWidth));
    setEditorWidth(clampedWidth);
  };
  
  const handleMouseUp = () => {
    isResizing.current = false;
    document.removeEventListener('mousemove', handleMouseMove);
    document.removeEventListener('mouseup', handleMouseUp);
  };
  
  // 图表类型检测函数
  const detectChartType = (code) => {
    if (!code) return 'flowchart';
    
    const codeLines = code.toLowerCase().split('\n');
    const firstLine = codeLines[0]?.trim();
    
    if (firstLine?.startsWith('requirementdiagram')) return 'requirement';
    if (firstLine?.startsWith('flowchart') || firstLine?.startsWith('graph')) return 'flowchart';
    if (firstLine?.startsWith('sequencediagram')) return 'sequence';
    if (firstLine?.startsWith('classdiagram')) return 'class';
    if (firstLine?.startsWith('statediagram')) return 'state';
    if (firstLine?.startsWith('erdiagram')) return 'er';
    if (firstLine?.startsWith('gantt')) return 'gantt';
    if (firstLine?.startsWith('pie')) return 'pie';
    if (firstLine?.startsWith('journey')) return 'journey';
    if (firstLine?.startsWith('gitgraph')) return 'git';
    if (firstLine?.startsWith('c4context')) return 'c4context';
    if (firstLine?.startsWith('c4container')) return 'c4container';
    if (firstLine?.startsWith('c4component')) return 'c4component';
    if (firstLine?.startsWith('c4deployment')) return 'c4deployment';
    if (firstLine?.startsWith('mindmap')) return 'mindmap';
    if (firstLine?.startsWith('timeline')) return 'timeline';
    
    return 'flowchart';
  };
  
  // 模板名称映射
  const templateNameMap = {
    '基本流程图': 'flowchart_basic',
    '用户登录流程': 'flowchart_user_login',
    '产品开发流程': 'flowchart_product_dev',
    'API工作流': 'flowchart_api_workflow',
    '订单处理流程': 'flowchart_api_workflow',
    '客户支持流程': 'flowchart_user_journey',
    '缺陷跟踪流程': 'flowchart_security_audit',
    '部署流程': 'flowchart_devops',
    '会议流程': 'flowchart_decision_tree',
    '决策流程': 'flowchart_decision_tree',
    'API调用流程': 'flowchart_api_workflow',
    '数据处理流程': 'flowchart_data_pipeline',
    '微服务架构': 'flowchart_microservices',
    'DevOps流程': 'flowchart_devops',
    '安全审计流程': 'flowchart_security_audit',
    '用户旅程图': 'flowchart_user_journey',
    '决策树': 'flowchart_decision_tree',
    '备份策略': 'flowchart_backup_strategy',
    '子流程图': 'subprocessFlowchart',
    '基本时序图': 'sequence_basic',
    '用户认证时序': 'sequence_user_auth',
    'API集成时序': 'sequence_api_call',
    'API调用时序': 'sequence_api_call',
    '订单处理时序': 'sequence_order_process',
    '支付流程时序': 'sequence_order_process',
    '通知系统时序': 'sequence_message_queue',
    '数据同步时序': 'sequence_data_sync',
    '错误处理时序': 'sequence_error_handling',
    '微服务调用时序': 'sequence_microservice_interaction',
    '第三方集成时序': 'sequence_api_call',
    '消息队列时序': 'sequence_message_queue',
    '复杂时序图': 'sequence_microservice_interaction',
    '循环时序图': 'sequence_data_sync',
    '基本类图': 'class_basic',
    '继承关系图': 'class_basic',
    '接口实现图': 'class_basic',
    '用户系统类图': 'class_basic',
    '订单系统类图': 'class_ecommerce',
    '产品管理类图': 'class_ecommerce',
    '通知系统类图': 'class_content_management',
    '基本状态图': 'state_basic',
    '复杂状态图': 'state_order_lifecycle',
    '支付状态图': 'state_payment_processing',
    '订单状态图': 'state_order_lifecycle',
    '用户状态图': 'state_user_status',
    '任务状态图': 'state_project_management',
    '基本ER图': 'er_basic',
    '复杂ER图': 'er_ecommerce',
    '库存管理ER图': 'er_basic',
    '用户管理ER图': 'er_basic',
    '订单管理ER图': 'er_ecommerce',
    '内容管理ER图': 'er_basic',
    '基本甘特图': 'gantt_basic',
    '项目甘特图': 'gantt_software_development',
    '项目计划甘特图': 'gantt_basic',
    '移动应用开发甘特图': 'gantt_mobile_app',
    '营销活动甘特图': 'gantt_marketing_campaign',
    '研究项目甘特图': 'gantt_research_project',
    '基本饼图': 'pie_product_market_share',
    '详细饼图': 'pie_budget_allocation',
    '功能使用饼图': 'pie_feature_usage',
    '产品市场份额饼图': 'pie_product_market_share',
    '预算分配饼图': 'pie_budget_allocation',
    '用户设备分布饼图': 'pie_user_device_distribution',
    '流量来源饼图': 'pie_traffic_sources',
    '产品生态系统关系图': 'graph_product_ecosystem',
    '微服务架构关系图': 'graph_microservices_architecture',
    '数据流关系图': 'graph_data_flow',
    '业务流程关系图': 'graph_business_process',
    '决策支持关系图': 'graph_decision_support',
    '基本用户旅程': 'journey_user_onboarding',
    '详细用户旅程': 'journey_customer_support',
    '用户入门旅程图': 'journey_user_onboarding',
    '客户支持旅程图': 'journey_customer_support',
    '产品购买旅程图': 'journey_product_purchase',
    '员工入职旅程图': 'journey_employee_onboarding',
    '功能采用旅程图': 'journey_feature_adoption',
    '用户认证需求图': 'requirement_user_authentication',
    '支付系统需求图': 'requirement_payment_system',
    '数据隐私需求图': 'requirement_data_privacy',
    '性能需求图': 'requirement_performance',
    '移动兼容性需求图': 'requirement_mobile_compatibility',
    'Git提交工作流': 'git_commit_workflow',
    'Git发布流程': 'git_release_process',
    'Git功能开发流程': 'git_feature_development',
    'Git协作工作流': 'git_collaborative_workflow',
    'Git缺陷修复工作流': 'git_bug_fix_workflow',
    'C4上下文图': 'c4_system_context',
    'C4容器图': 'c4_container_diagram',
    'C4组件图': 'c4_component_diagram',
    'C4部署图': 'c4_deployment_diagram',
    'C4系统上下文图': 'c4_system_context',
    '基本思维导图': 'mindmap_product_strategy',
    '复杂思维导图': 'mindmap_user_research',
    '产品策略思维导图': 'mindmap_product_strategy',
    '用户研究思维导图': 'mindmap_user_research',
    '产品功能思维导图': 'mindmap_product_features',
    '竞争分析思维导图': 'mindmap_competitive_analysis',
    '项目管理思维导图': 'mindmap_project_management',
    '基本时间线': 'timeline_product_launch',
    '项目时间线': 'timeline_project_milestones',
    '产品发布时间线': 'timeline_product_launch',
    '项目里程碑时间线': 'timeline_project_milestones',
    '营销活动时间线': 'timeline_marketing_campaign',
    '软件开发时间线': 'timeline_software_development',
    '团队建设时间线': 'timeline_team_building'
  };
  
  // 显示图表文档
  const showChartDocumentation = () => {
    const chartType = detectChartType(code);
    setCurrentChartType(chartType);
    setShowChartDocs(true);
  };
  
  // 隐藏图表文档
  const hideChartDocumentation = () => {
    setShowChartDocs(false);
  };
  
  // 加载模板
  const loadTemplate = (templateId) => {
    const englishTemplateName = templateNameMap[templateId];
    if (englishTemplateName && templates[englishTemplateName]) {
      setCode(templates[englishTemplateName]);
    } else {
      console.warn(`未找到模板: ${templateId}, 英文映射: ${englishTemplateName}`);
      let defaultTemplate = templates.flowchart_basic;
      
      if (templateId.includes('时序')) {
        defaultTemplate = templates.sequence_basic;
      } else if (templateId.includes('类图')) {
        defaultTemplate = templates.class_basic;
      } else if (templateId.includes('状态')) {
        defaultTemplate = templates.state_basic;
      } else if (templateId.includes('ER')) {
        defaultTemplate = templates.er_basic;
      } else if (templateId.includes('甘特')) {
        defaultTemplate = templates.gantt_basic;
      } else if (templateId.includes('饼图')) {
        defaultTemplate = templates.pie_product_market_share;
      } else if (templateId.includes('旅程')) {
        defaultTemplate = templates.journey_user_onboarding;
      } else if (templateId.includes('C4')) {
        defaultTemplate = templates.c4_system_context;
      } else if (templateId.includes('思维导图')) {
        defaultTemplate = templates.mindmap_product_strategy;
      } else if (templateId.includes('时间线')) {
        defaultTemplate = templates.timeline_product_launch;
      } else if (templateId.includes('Git')) {
        defaultTemplate = templates.git_commit_workflow;
      } else if (templateId.includes('需求')) {
        defaultTemplate = templates.requirement_user_authentication;
      } else if (templateId.includes('关系图')) {
        defaultTemplate = templates.graph_product_ecosystem;
      }
      
      setCode(defaultTemplate);
    }
  };
  
  // Toggle category expansion
  const toggleCategory = (categoryId) => {
    setExpandedCategories(prev => ({
      ...prev,
      [categoryId]: !prev[categoryId]
    }));
  };
  
  // Toggle sidebar
  const toggleSidebar = () => {
    setSidebarCollapsed(!sidebarCollapsed);
  };
  
  // Get templates by category
  const getTemplatesByCategory = (categoryId) => {
    const category = templateCategories[categoryId];
    if (!category) return [];
    
    return category.templates.map(templateName => {
      return {
        id: templateName,
        name: templateName,
        description: `${category.name}图表模板：${templateName}`
      };
    });
  };
  
  // Copy code to clipboard
  const copyCode = async () => {
    try {
      await navigator.clipboard.writeText(code);
      alert('代码已复制到剪贴板！');
    } catch (err) {
      console.error('Failed to copy code:', err);
    }
  };
  
  // Download diagram as SVG
  const downloadDiagram = () => {
    if (!diagramRef.current) return;
    
    const svgElement = diagramRef.current.querySelector('svg');
    if (!svgElement) {
      alert('请先创建图表');
      return;
    }
    
    const svgData = new XMLSerializer().serializeToString(svgElement);
    const svgBlob = new Blob([svgData], { type: 'image/svg+xml;charset=utf-8' });
    const svgUrl = URL.createObjectURL(svgBlob);
    
    const downloadLink = document.createElement('a');
    downloadLink.href = svgUrl;
    downloadLink.download = 'mermaid-diagram.svg';
    document.body.appendChild(downloadLink);
    downloadLink.click();
    document.body.removeChild(downloadLink);
    URL.revokeObjectURL(svgUrl);
  };
  
  // Reset to default template
  const resetCode = () => {
    setCode(templates.flowchart);
  };
  
  // 缩放功能
  const zoomIn = () => {
    if (scale < maxScale) {
      const newScale = Math.min(scale + zoomStep, maxScale);
      setScale(newScale);
      applyZoom(newScale);
    }
  };
  
  const zoomOut = () => {
    if (scale > minScale) {
      const newScale = Math.max(scale - zoomStep, minScale);
      setScale(newScale);
      applyZoom(newScale);
    }
  };
  
  const applyZoom = (newScale) => {
    if (diagramRef.current) {
      diagramRef.current.style.transform = `scale(${newScale}) translate(${translateX}px, ${translateY}px)`;
      diagramRef.current.style.transformOrigin = 'center center';
      
      if (showMiniMap) {
        setTimeout(() => {
          updateMiniMapViewport();
        }, 100);
      }
    }
  };
  
  // 导览小窗相关函数
  const updateMiniMap = () => {
    if (!miniMapRef.current || !diagramRef.current) return;
    
    const svg = diagramRef.current.querySelector('svg');
    if (!svg) {
      setShowMiniMap(false);
      return;
    }
    
    miniMapRef.current.innerHTML = '';
    
    const miniMapContent = document.createElement('div');
    miniMapContent.className = 'mini-map-content';
    
    const miniSvg = svg.cloneNode(true);
    miniSvg.removeAttribute('id');
    miniSvg.style.width = '100%';
    miniSvg.style.height = '100%';
    miniSvg.style.display = 'block';
    miniMapContent.appendChild(miniSvg);
    
    const viewport = document.createElement('div');
    viewport.className = 'mini-map-viewport';
    viewportRef.current = viewport;
    
    miniMapRef.current.appendChild(miniMapContent);
    miniMapRef.current.appendChild(viewport);
    
    updateMiniMapViewport();
  };
  
  const updateMiniMapViewport = () => {
    if (!miniMapRef.current || !diagramRef.current || !viewportRef.current) return;
    
    const svg = diagramRef.current.querySelector('svg');
    if (!svg) return;
    
    const diagramContainer = document.querySelector('.diagram-container');
    const svgRect = svg.getBoundingClientRect();
    const containerRect = diagramContainer.getBoundingClientRect();
    
    const miniMapContent = miniMapRef.current.querySelector('.mini-map-content');
    if (!miniMapContent) return;
    
    const scaleX = miniMapContent.clientWidth / svgRect.width;
    const scaleY = miniMapContent.clientHeight / svgRect.height;
    
    const viewportWidth = Math.min(containerRect.width * scaleX, miniMapContent.clientWidth);
    const viewportHeight = Math.min(containerRect.height * scaleY, miniMapContent.clientHeight);
    
    const offsetX = Math.max(0, Math.min((-translateX * scaleX), miniMapContent.clientWidth - viewportWidth));
    const offsetY = Math.max(0, Math.min((-translateY * scaleY), miniMapContent.clientHeight - viewportHeight));
    
    viewportRef.current.style.width = `${viewportWidth}px`;
    viewportRef.current.style.height = `${viewportHeight}px`;
    viewportRef.current.style.left = `${offsetX}px`;
    viewportRef.current.style.top = `${offsetY}px`;
  };
  
  const setupMiniMapDrag = () => {
    if (!viewportRef.current) return;
    
    let isDragging = false;
    let startX, startY;
    
    const handleMouseDown = (e) => {
      isDragging = true;
      startX = e.clientX - parseInt(viewportRef.current.style.left || 0);
      startY = e.clientY - parseInt(viewportRef.current.style.top || 0);
      e.preventDefault();
    };
    
    const handleMouseMove = (e) => {
      if (!isDragging) return;
      
      const miniMapContent = miniMapRef.current.querySelector('.mini-map-content');
      if (!miniMapContent) return;
      
      let x = e.clientX - startX;
      let y = e.clientY - startY;
      
      const contentRect = miniMapContent.getBoundingClientRect();
      const viewportWidth = parseInt(viewportRef.current.style.width || 0);
      const viewportHeight = parseInt(viewportRef.current.style.height || 0);
      
      const maxX = contentRect.width - viewportWidth;
      const maxY = contentRect.height - viewportHeight;
      
      x = Math.max(0, Math.min(x, maxX));
      y = Math.max(0, Math.min(y, maxY));
      
      viewportRef.current.style.left = `${x}px`;
      viewportRef.current.style.top = `${y}px`;
      
      const svg = diagramRef.current.querySelector('svg');
      if (svg) {
        const svgRect = svg.getBoundingClientRect();
        const scaleX = miniMapContent.clientWidth / svgRect.width;
        const scaleY = miniMapContent.clientHeight / svgRect.height;
        
        const newTranslateX = -x / scaleX;
        const newTranslateY = -y / scaleY;
        
        setTranslateX(newTranslateX);
        setTranslateY(newTranslateY);
        
        diagramRef.current.style.transform = `scale(${scale}) translate(${newTranslateX}px, ${newTranslateY}px)`;
      }
    };
    
    const handleMouseUp = () => {
      isDragging = false;
    };
    
    viewportRef.current.addEventListener('mousedown', handleMouseDown);
    document.addEventListener('mousemove', handleMouseMove);
    document.addEventListener('mouseup', handleMouseUp);
    
    return () => {
      if (viewportRef.current) {
        viewportRef.current.removeEventListener('mousedown', handleMouseDown);
      }
      document.removeEventListener('mousemove', handleMouseMove);
      document.removeEventListener('mouseup', handleMouseUp);
    };
  };
  
  const toggleMiniMap = () => {
    setShowMiniMap(!showMiniMap);
  };
  
  // 背景颜色和图案处理
  const handleBackgroundColorChange = (e) => {
    const color = e.target.value;
    setBackgroundColor(color);
    applyBackgroundColor(color);
  };
  
  const handleBackgroundPatternChange = (pattern) => {
    setBackgroundPattern(pattern);
    applyBackgroundPattern(pattern);
  };
  
  const applyBackgroundColor = (color) => {
    const diagramContainer = document.querySelector('.diagram-container');
    if (diagramContainer) {
      diagramContainer.classList.remove('bg-white', 'bg-light-gray', 'bg-dark-gray');
      diagramContainer.style.backgroundColor = color;
    }
  };
  
  const applyBackgroundPattern = (pattern) => {
    const diagramContainer = document.querySelector('.diagram-container');
    if (diagramContainer) {
      diagramContainer.classList.remove('bg-pattern-dots', 'bg-pattern-lines', 'bg-pattern-grid');
      
      if (pattern !== 'none') {
        diagramContainer.classList.add(`bg-pattern-${pattern}`);
      }
    }
  };
  
  // 初始化时应用背景设置
  useEffect(() => {
    applyBackgroundColor(backgroundColor);
    applyBackgroundPattern(backgroundPattern);
  }, []);
  
  // 处理Monaco编辑器挂载
  const handleEditorMount = (editor, monaco) => {
    defineMermaidLanguage(monaco);
    monaco.editor.setTheme('mermaid');
    setEditorReady(true);
  }
  
  // Initialize with no categories expanded for compact view
  useEffect(() => {
    const initialExpanded = {};
    Object.keys(templateCategories).forEach(catId => {
      initialExpanded[catId] = false;
    });
    setExpandedCategories(initialExpanded);
  }, []);

  return (
    <div className="mermaid-editor">
      <div className="editor-container">
        <div className="code-section" style={{ width: `${editorWidth}%` }}>
          <div className="section-header">
            <h3><Code size={16} /> Mermaid 代码</h3>
            <div className="section-actions">
              <Tooltip content="复制当前代码到剪贴板" position="bottom" offset={8}>
                <button onClick={copyCode} className="btn btn-icon">
                  <Copy size={16} />
                </button>
              </Tooltip>
              <Tooltip content="查看Mermaid图表语法文档" position="bottom" offset={8}>
                <button 
                  className="btn btn-icon"
                  onClick={showChartDocumentation}
                >
                  <Info size={16} />
                </button>
              </Tooltip>
            </div>
          </div>
          <Editor
            height="100%"
            defaultLanguage="mermaid"
            value={code}
            onChange={(value) => setCode(value || '')}
            theme="mermaid"
            loading={<div className="editor-loading">正在加载Monaco编辑器...</div>}
            onMount={handleEditorMount}
            options={{
              minimap: { enabled: false },
              fontSize: 14,
              lineNumbers: 'on',
              wordWrap: 'on',
              automaticLayout: true,
              scrollBeyondLastLine: false,
            }}
          />
        </div>

        <div className="resize-handle" 
          onMouseDown={handleResizeStart}
        />

        <div className="preview-section" style={{ width: `${100 - editorWidth}%` }}>
          <div className="section-header">
            <h3><Eye size={16} /> 图表预览</h3>
            <div className="section-actions">
              <div className="theme-selector">
                <label htmlFor="theme-select" className="control-label">主题:</label>
                <Tooltip 
                  content={`选择主题 - 当前: ${mermaidThemes[currentTheme]?.name || currentTheme}`}
                  position="bottom"
                  offset={8}
                >
                  <select 
                    id="theme-select"
                    className="theme-select"
                    value={currentTheme}
                    onChange={(e) => handleThemeChange(e.target.value)}
                  >
                    {Object.keys(mermaidThemes).map(themeId => (
                      <option key={themeId} value={themeId}>
                        {mermaidThemes[themeId].name}
                      </option>
                    ))}
                  </select>
                </Tooltip>
                <Tooltip content="自定义主题颜色" position="bottom" offset={8}>
                  <button 
                    className="btn btn-icon custom-theme-btn"
                    onClick={openCustomThemeModal}
                    style={{ marginLeft: '10px' }}
                  >
                    <Palette size={16} />
                  </button>
                </Tooltip>
              </div>
              <Tooltip content="下载当前图表为PNG图片" position="bottom" offset={8}>
                <button onClick={downloadDiagram} className="btn btn-icon">
                  <Download size={16} />
                </button>
              </Tooltip>
            </div>
            {isLoading && <span className="loading">渲染中...</span>}
          </div>
          <div className="diagram-container">
            {error && (
              <div className="error-message">
                <strong>渲染错误：</strong> {error}
              </div>
            )}
            <div 
              ref={diagramRef} 
              className="mermaid-diagram"
              style={{ minHeight: '200px' }}
            />
            
            {/* 导览小窗 */}
            {showMiniMap && (
              <div className="mini-map" ref={miniMapRef}>
                {/* 内容将通过updateMiniMap函数动态添加 */}
              </div>
            )}
            
            {/* 导览小窗切换按钮 */}
            {!showMiniMap && (
              <Tooltip content="显示导航小地图" position="left" offset={12}>
                <button className="mini-map-toggle" onClick={toggleMiniMap}>
                  <Eye size={16} />
                </button>
              </Tooltip>
            )}
          </div>
          
          {/* 添加预览控制区域 */}
          <div className="preview-controls">
            <div className="zoom-controls">
              <Tooltip content={`缩小 - 当前缩放: ${Math.round(scale * 100)}%`} position="top" offset={8}>
                <button
                  className="zoom-btn"
                  onClick={zoomOut}
                  disabled={scale <= minScale}
                >
                  <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                    <line x1="5" y1="12" x2="19" y2="12"></line>
                  </svg>
                </button>
              </Tooltip>
              <Tooltip content={`放大 - 当前缩放: ${Math.round(scale * 100)}%`} position="top" offset={8}>
                <button
                  className="zoom-btn"
                  onClick={zoomIn}
                  disabled={scale >= maxScale}
                >
                  <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                    <line x1="12" y1="5" x2="12" y2="19"></line>
                    <line x1="5" y1="12" x2="19" y2="12"></line>
                  </svg>
                </button>
              </Tooltip>
            </div>
            
            <Tooltip content={`选择背景颜色 - 当前: ${backgroundColor}`} position="top" offset={8}>
              <div className="color-preview-wrapper">
                <div className="color-picker-wrapper">
                  <input 
                    type="color" 
                    id="bg-color-picker" 
                    className="color-picker"
                    value={backgroundColor}
                    onChange={handleBackgroundColorChange}
                  />
                </div>
              </div>
            </Tooltip>
            
            <div className="pattern-controls">
              <Tooltip content="无背景图案" position="top" offset={8}>
                <button 
                  className={`control-btn pattern-btn ${backgroundPattern === 'none' ? 'active' : ''}`}
                  onClick={() => handleBackgroundPatternChange('none')}
                >
                  <div className="pattern-preview none-preview"></div>
                </button>
              </Tooltip>
              <Tooltip content="点状背景" position="top" offset={8}>
                <button 
                  className={`control-btn pattern-btn ${backgroundPattern === 'dots' ? 'active' : ''}`}
                  onClick={() => handleBackgroundPatternChange('dots')}
                >
                  <div className="pattern-preview dots-preview"></div>
                </button>
              </Tooltip>
              <Tooltip content="线状背景" position="top" offset={8}>
                <button 
                  className={`control-btn pattern-btn ${backgroundPattern === 'lines' ? 'active' : ''}`}
                  onClick={() => handleBackgroundPatternChange('lines')}
                >
                  <div className="pattern-preview lines-preview"></div>
                </button>
              </Tooltip>
              <Tooltip content="网格背景" position="top" offset={8}>
                <button 
                  className={`control-btn pattern-btn ${backgroundPattern === 'grid' ? 'active' : ''}`}
                  onClick={() => handleBackgroundPatternChange('grid')}
                >
                  <div className="pattern-preview grid-preview"></div>
                </button>
              </Tooltip>
            </div>
          </div>
        </div>
      </div>
      
      {/* 图表提示文档模态框 */}
      {showChartDocs && (
        <div className="chart-docs-modal">
          <div className="chart-docs-content">
            <div className="chart-docs-header">
              <h2>{chartDocs[currentChartType]?.name || '图表文档'}</h2>
              <Tooltip content="关闭文档窗口" position="left" offset={12}>
                <button className="close-button" onClick={hideChartDocumentation}>
                  <X size={20} />
                </button>
              </Tooltip>
            </div>
            
            <div className="chart-docs-body">
              {chartDocs[currentChartType] && (
                <>
                  <div className="chart-docs-section">
                    <h3>描述</h3>
                    <p>{chartDocs[currentChartType].description}</p>
                  </div>
                  
                  <div className="chart-docs-section">
                    <h3>基本语法</h3>
                    <pre className="syntax-example">{chartDocs[currentChartType].syntax}</pre>
                  </div>
                  
                  <div className="chart-docs-section">
                    <h3>参数说明</h3>
                    <table className="parameters-table">
                      <thead>
                        <tr>
                          <th>参数</th>
                          <th>说明</th>
                        </tr>
                      </thead>
                      <tbody>
                        {chartDocs[currentChartType].parameters.map((param, index) => (
                          <tr key={index}>
                            <td>{param.name}</td>
                            <td>{param.description}</td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                  
                  <div className="chart-docs-section">
                    <h3>示例</h3>
                    <pre className="code-example">{chartDocs[currentChartType].example}</pre>
                  </div>
                  
                  <div className="chart-docs-section">
                    <h3>使用技巧</h3>
                    <ul>
                      {chartDocs[currentChartType].tips.map((tip, index) => (
                        <li key={index}>{tip}</li>
                      ))}
                    </ul>
                  </div>
                </>
              )}
            </div>
          </div>
        </div>
      )}
      
      {/* 自定义主题模态框 */}
      {showCustomThemeModal && (
        <div className="custom-theme-modal">
          <div className="custom-theme-content">
            <div className="custom-theme-header">
              <h2>自定义主题配置</h2>
              <Tooltip content="关闭自定义主题窗口" position="left" offset={12}>
                <button className="close-button" onClick={closeCustomThemeModal}>
                  <X size={20} />
                </button>
              </Tooltip>
            </div>
            
            <div className="custom-theme-body">
              <div className="color-inputs-grid">
                {Object.entries(customThemeColors).map(([key, value]) => (
                  <div key={key} className="color-input-group">
                    <label className="color-label">
                      {themeVariableLabels[key] || key}:
                    </label>
                    <div className="color-input-wrapper">
                      <input
                        type="color"
                        value={value}
                        onChange={(e) => handleCustomColorChange(key, e.target.value)}
                        className="color-input"
                      />
                      <input
                        type="text"
                        value={value}
                        onChange={(e) => handleCustomColorChange(key, e.target.value)}
                        className="color-text-input"
                        placeholder="#000000"
                      />
                    </div>
                  </div>
                ))}
              </div>
              
              <div className="custom-theme-actions">
                <button className="btn btn-secondary" onClick={resetCustomTheme}>
                  重置为默认值
                </button>
                <button className="btn btn-primary" onClick={applyCustomTheme}>
                  应用主题
                </button>
              </div>
              
              <div className="theme-preview">
                <h3>主题预览</h3>
                <div className="preview-diagram" style={{ backgroundColor: customThemeColors.background }}>
                  <div className="preview-node" style={{ 
                    backgroundColor: customThemeColors.primaryColor,
                    borderColor: customThemeColors.primaryBorderColor,
                    color: customThemeColors.primaryTextColor
                  }}>
                    节点示例
                  </div>
                  <div className="preview-line" style={{ 
                    backgroundColor: customThemeColors.lineColor 
                  }}></div>
                  <div className="preview-node-secondary" style={{ 
                    backgroundColor: customThemeColors.secondaryColor,
                    color: customThemeColors.nodeTextColor
                  }}>
                    次要节点
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default MermaidEditor;